<?PHP

ini_set('include_path',ini_get('include_path').':/home/mermexi/local/lib/PEAR:'); 

require_once('config.php');

// JSON init
require_once('JSON.php');
$json = new Services_JSON();

// DB init
require_once('DB.php');
$db = DB::connect(sprintf('mysql://%s:%s@%s/%s', HM_DBUSER, HM_DBPASS, HM_DBHOST, HM_DBNAME));
if (PEAR::isError($db)) { die ($db->getMessage()); }
$db->setFetchMode(DB_FETCHMODE_ASSOC);

// $user init
if (isset($_COOKIE['userid'])) $user = $db->getRow('SELECT * FROM users WHERE user_id="' . $_COOKIE['userid'] . '"');
if (!isset($user)) $user = array('user_id' => '', 'name' => '', 'categories' => serialize(array()));
$user['categories'] = unserialize($user['categories']);

function getPuzzle () {

 global $user, $db;

 if ($user['user_id'] == '') return $db->getRow('SELECT * FROM puzzles ORDER BY RAND() LIMIT 1');
 if (count($user['categories'])) $where_clause = ' WHERE puzzle_cat IN (' . join(',', $user['categories']) . ') ';
 $puzzles_sql = 'SELECT puzzles.puzzle_id, puzzles.puzzle_lang1, puzzles.puzzle_lang2 FROM puzzles LEFT JOIN scores ON puzzles.puzzle_id=scores.puzzle_id && scores.user_id="' . $user['user_id'] . '" ' . $where_clause . ' ORDER BY scores.puzzle_score, RAND() LIMIT 5';
 $puzzles = $db->getAll($puzzles_sql);
 return $puzzles[array_rand($puzzles)];

}


function updateScore ( $puzzle_score, $puzzle_id ) {

 // insert row into scores with passed data

 global $db, $user;

 if ($user['user_id'] == '') return false;

 $existing_score = $db->getAll('SELECT * FROM scores WHERE user_id="' . $user['user_id'] . '" && puzzle_id=' . $puzzle_id);
 if ($existing_score) $db->query('UPDATE scores SET puzzle_score=' . $puzzle_score . ' WHERE user_id="' . $user['user_id'] . '" && puzzle_id=' . $puzzle_id);
 else $db->query('INSERT INTO scores SET puzzle_score=' . $puzzle_score . ', user_id="' . $user['user_id'] . '", puzzle_id=' . $puzzle_id);

 return true;

}

function getWordList ( ) {

 global $db, $user;

 $puzzle_list = array();

 if ($user['user_id'] == '') {

  // just return all the words

  $get_puzzles_sql = sprintf('SELECT * FROM puzzles;');
  $all_puzzles = $db->getAll($get_puzzles_sql);
  foreach ($all_puzzles as $puzzle) {
   $puzzle_list[] = array($puzzle['puzzle_lang1'], $puzzle['puzzle_lang2']);
  } 

 }

 else {

  // return a customized word list

  if (count($user['categories'])) {
   $where_clause = sprintf(' WHERE puzzle_cat IN (%s) ', join(',', $user['categories']) );
  } else {
   $where_clause = '';
  }
  $puzzles_sql = 'SELECT puzzles.puzzle_lang1, puzzles.puzzle_lang2, scores.puzzle_score FROM puzzles LEFT JOIN scores ON puzzles.puzzle_id=scores.puzzle_id && scores.user_id="' . $user['user_id'] . '" ' . $where_clause;
  $custom_puzzles = $db->getAll($puzzles_sql);
  foreach ($custom_puzzles as $puzzle) {
   $repeat = max(floor((1-$puzzle['puzzle_score'])*100), 1);

   // we want puzzles with lower scores to be presented more times in the flashcard mode, so we weight the list by
   // adding more instances of puzzles that have lower scores... kinda cheezy, but it works.

   //var_dump('puzzle_score = ' . $puzzle['puzzle_score'] . ' :: repeat = ' . $repeat);
   for (;$repeat > 0; $repeat--) {
    $puzzle_list[] = array($puzzle['puzzle_lang1'], $puzzle['puzzle_lang2']);
   }
  }
 } 

 return $puzzle_list;

}


$cmd = $_REQUEST['cmd'];

if ($cmd == 'ajaxrequest') {

 $ajaxcmd = $_REQUEST['ajaxcmd'];

 switch ($ajaxcmd) {

  case 'getNewPuzzle':

   $puzzle = getPuzzle(); 
   $response = array('exitCode' => 0, 'exitMessage' => 'Puzzle loaded!', 'id' => $puzzle['puzzle_id'], 'lang1' => $puzzle['puzzle_lang1'], 'lang2' => $puzzle['puzzle_lang2']);
   echo $json->encode($response);
    
 // expect to return exitCode, exitMessage, lang1, lang2
 // exitCode 0 is success

  break;

  case 'updateScore':
   if (updateScore($_POST['score'], $_POST['puzzle_id'])) {
    $response = array('exitCode' => 0, 'exitMessage' => 'Score updated!');
   } else {
    $response = array('exitCode' => 1, 'exitMessage' => 'Score not updated. Try editing your preferences first.');
   }
   echo $json->encode($response);
   break;

  case 'getWordList':
   $wordlist = getWordList();
   $response = array('exitCode' => 0, 'exitMessage' => 'Wordlist loaded!', 'wordlist' => $wordlist);
   echo $json->encode($response);
   break;

  default:
  break;

 }

}

?>
